
// 微信公众号授权
function wxAuthorize(that) {
	/**
	 * 判断在微信浏览器下 是否获取code
	 */
	if(that.$config.getWxCode && that.$filter.isWeiXinBrowser()){
		// 地址解析
		let link = window.location.href;
		let code = getUrlParams("code");  
		
		// 已经授权登录过的就不用再授权了
		if (that.$store.state.vuex_token) return;
		
		// 如果拿到code，调用授权接口，没有拿到就跳转微信授权链接获取
		if (code) {
			that.$u.api.getOAuth2UserInfo({code : code, lang : 'zh_CN'}).then(res => {
				console.log(res);
				// 赋值用户信息
				let userInfo = {};
				userInfo.avatarUrl = res.data.headImgUrl;
				userInfo.nickName = res.data.nickname;
				userInfo.gender = res.data.sex;
				userInfo.country = res.data.country;
				userInfo.province = res.data.province;
				userInfo.city = res.data.city;
				that.$u.vuex('vuex_openid', res.data.openId);
				that.$u.vuex('vuex_user', userInfo);
				that.$u.vuex('vuex_hasLogin', true);
				that.$u.vuex('vuex_token', 'vuex_token');
			})
		} else {
		    let appid = that.$config.wxAppid;
		    let uri = encodeURIComponent(link);
			let wxScope = that.$config.wxScope;
		    let authURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=${wxScope}&state=123#wechat_redirect`;
		    window.location.href = authURL;
		}
	}
}

//获取参数
function getUrlParams(name){
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r!=null)return  unescape(r[2]); return null;
}

module.exports = {
	wxAuthorize
}